import type { LngLat } from 'mapbox-gl';

export class PositionMouse {
  map: mapboxgl.Map | null = null;

  private lastCallTime = 0;
  private throttleDelay = 100;

  constructor(map: mapboxgl.Map) {
    this.map = map;
  }

  onPositionChange: (coords: LngLat) => void = () => {};
  onZoomChange: (zoom: number) => void = () => {};

  private moveHandler = (e: mapboxgl.MapMouseEvent) => {
    const now = Date.now();
    if (now - this.lastCallTime < this.throttleDelay) {
      return;
    }
    this.lastCallTime = now;
    const coords = e.lngLat;
    this.onPositionChange(coords);
  };

  // TODO not effect
  private leaveHandler = () => {
    if (!this.map) return;
    const center = this.map.getCenter();
    this.onPositionChange(center);
  };

  private zoomHandler = () => {
    if (!this.map) return;
    const z = this.map.getZoom();
    this.onZoomChange(z);
  };

  startMouse() {
    if (!this?.map) return;
    this.map?.on('mousemove', this.moveHandler);
    this.map?.on('mouseleave', this.leaveHandler);
    this.map?.on('zoom', this.zoomHandler);
  }

  stopMouse() {
    this.map?.off('mousemove', this.moveHandler);
    this.map?.off('mouseleave', this.leaveHandler);
    this.map?.off('zoom', this.zoomHandler);
  }
}
